package com.springboot.frame.backup;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Cors 的spring-boot启动器
 *
 * @author TaoYu MaYing
 */
@Configuration
@EnableConfigurationProperties(BackUpProperties.class)
@ConditionalOnProperty(name = "database.backup.enabled")
@EnableScheduling
public class BackUpAutoConfiguration {
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    private final BackUpProperties properties;

    public BackUpAutoConfiguration(BackUpProperties properties) {
        this.properties = properties;
    }

    @Bean
    public JobDetail backUpQuartzDetail() {
        JobDetail jobDetail = JobBuilder.newJob(BackUpDatabaseJob.class).withIdentity("job-back-up-databases", "job-group-back-up-databases").storeDurably().build();
        Map<String, Object> map = new HashMap<>(2);
        map.put("properties", properties);
        map.put("dataSource", dataSource);
        jobDetail.getJobDataMap().putAll(map);
        return jobDetail;
    }

    @Bean
    public Trigger backUpQuartzTrigger() {
        // 触发器
        return TriggerBuilder
                .newTrigger().withIdentity("trigger-back-up-databases", "trigger-group-back-up-databases")
                .withSchedule(CronScheduleBuilder.cronSchedule(properties.getCron()))
                .forJob(backUpQuartzDetail())
                .build();
    }

}
